package com.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        // 开发环境：允许所有域名
        config.addAllowedOriginPattern("*");

        // 生产环境：明确列出允许的域名
        // config.setAllowedOriginPatterns(Arrays.asList(
        //     "http://your-domain.com",
        //     "https://your-domain.com"
        // ));

        config.setAllowCredentials(true);
        config.addAllowedMethod("*");  // 允许所有 HTTP 方法
        config.addAllowedHeader("*");  // 允许所有请求头

        // 暴露需要前端访问的响应头
        config.setExposedHeaders(Arrays.asList(
                "Authorization",
                "Content-Type",
                "Content-Disposition"
        ));

        // 缓存预检请求结果 1 小时，减少 OPTIONS 请求
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}